import "./index.scss";
import { useState, useEffect } from "react";
import ReactQuill from "react-quill";
import { Button, Form, Input, Select, Space, Radio, Upload ,message} from "antd";
import { request } from "@/utils";
import { useSearchParams } from "react-router-dom";
import "react-quill/dist/quill.snow.css"; // 引入样式文件
import { useChannel } from "@/hooks/useChannel";
const { Option } = Select;
export default function Publish() {
  let [searchParams] = useSearchParams();
  let paramsId = searchParams.get("id");

  let changeRadio = (e) => {
    setRadio(e.target.value);
  };
  const [value, setValue] = useState("");
  const [radio, setRadio] = useState(1);
  const layout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
  };
  const tailLayout = {
    wrapperCol: { offset: 2, span: 22 },
  };
  useEffect(() => {
    if (paramsId) {
      request.get(`/mp/articles/${paramsId}`).then((res) => {
        console.log(res, "res");
        form.setFieldsValue({ ...res.data, type: res.data.cover.type });
        let arrImages = [];
        for (var i = 0; i < res.data.cover.images.length; i++) {
          arrImages.push({
            response: {
              data: { url: res.data.cover.images[i] },
            },
            thumbUrl: res.data.cover.images[i],
            url:res.data.cover.images[i],
          });
        }
        setFileList(arrImages);
      });
    }
  }, []);
  // cover : type images
  let [fileList, setFileList] = useState([]);
  let uploadChange = ({ fileList }) => {
    console.log(fileList, "file");
    if (fileList) {
      setFileList(fileList);
    }
  };

  const [form] = Form.useForm();
  let optionsWithDisabled = [
    { label: "单图", value: 1 },
    { label: "三图", value: 3 },
    { label: "无图", value: 0 },
  ];
  const onFinish = (values) => {
    let sendMsg = {
      ...values,
      cover: {
        type: radio,
        images: fileList.map((item) => item.response.data.url),
      },
    };
    if(paramsId){
      request.put(`/mp/articles/${paramsId}`,sendMsg).then((res)=>{
        message.success('修改成功')
      })
    }else{
      request.post("/mp/articles", sendMsg).then((res) => {
        message.success('添加成功')
      });
    }
    
  };
  let { itemList } = useChannel();

  return (
    <>
      <div className="publish">
        <Form
          {...layout}
          form={form}
          name="control-hooks"
          onFinish={onFinish}
          style={{ maxWidth: 600 }}
          initialValues={{ type: 1 }}
        >
          <Form.Item name="title" label="标题" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item
            name="channel_id"
            label="频道"
            rules={[{ required: true }]}
          >
            <Select placeholder="请选择" allowClear>
              {itemList.map((item) => (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="封面" name="type" rules={[{ required: true }]}>
            <Radio.Group options={optionsWithDisabled} onChange={changeRadio} />
          </Form.Item>
          {radio > 0 && (
            <Form.Item wrapperCol={{ offset: 2, span: 22 }}>
              <Upload
                name="image"
                action="http://geek.itheima.net/v1_0/upload"
                listType="picture-card"
                showUploadList
                onChange={uploadChange}
                maxCount={radio}
                fileList={fileList}
              >
                <span> 点击上传</span>
              </Upload>
            </Form.Item>
          )}

          <Form.Item name="content" label="内容" rules={[{ required: true }]}>
            <ReactQuill theme="snow" value={value} onChange={setValue} />
          </Form.Item>
          <Form.Item {...tailLayout}>
            <Space>
              <Button type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </>
  );
}
